// Copyright 2010 Jan Potoms. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


goog.require('extension.Module');


goog.provide('extension.reader.PollingModule');


goog.scope(function() {

  // namespaces
  var Module = extension.Module;
  
  
  
  
  
  /** Module that polls the unread count at regular intervals.
   * @extends {extension.Module}
   * @constructor 
   * 
   * @param {extension.Context} context The context this module lives in.
   */
  extension.reader.PollingModule = function (context) { 
    Module.call(this, context);  
    
    this.pollTime = this.context.getOption('refreshInterval')
    
    this.poll_();
    
  };
  var PollingModule = extension.reader.PollingModule;
  goog.inherits(PollingModule, Module);
  
  
  
  
  
  /** Holds the timer reference for polling.
   * @type {number} 
   */
  PollingModule.prototype.pollTimer = 0; 
  
  /** The interval at which to poll.
   * @type {number} 
   */
  PollingModule.prototype.pollTime;
  
  
  
  
  
  /** Schedules a next poll. If a poll is already scheduled it will be canceled.
   * @private
   */
  PollingModule.prototype.scheduleNextPoll_ = function () {
    
    if(this.pollTimer) {
      clearTimeout(this.pollTimer);
    }
    
    this.pollTimer = setTimeout(goog.bind(this.poll_, this), this.pollTime);
    
  };
  
  
  
  
  
  /** Performs the actual poll.
   * @private
   */
  PollingModule.prototype.poll_ = function () {
    
      this.getUnreadCount_();
      this.scheduleNextPoll_();
    
  };




  /** Gets the unread count.
   * @private
   */
  PollingModule.prototype.getUnreadCount_ = function () {
    
    var data = {
      'tag': /user\/[\d]+\/state\/com\.google\/reading-list/
    };

    this.context.request('googleReaderUnreadCounts', data, 
      function(response) {
        console.log(response);
      },
      function(response) {
        console.log(response);
      }
    );
    
  };
  
  
  
  
  
  /** @inheritDoc */
  PollingModule.prototype.dispose = function() {
    // no eventhandlers to remove
  };
  
  
  
});